package edu.uwlax.cs.oayonlinestore.client.gui.admin;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Widget;

import edu.uwlax.cs.oayonlinestore.client.OnlinestoreRService;
import edu.uwlax.cs.oayonlinestore.client.gui.Store;
import edu.uwlax.cs.oayonlinestore.client.utils.DefaultAsyncCallback;
import edu.uwlax.cs.oayonlinestore.client.utils.DekoTable;
import edu.uwlax.cs.oayonlinestore.client.utils.SwitchPage;
import edu.uwlax.cs.oayonlinestore.client.utils.TitlePage;
import edu.uwlax.cs.oayonlinestore.vo.CategoryVO;

public class PageAdminCategories extends TitlePage {

	private class CategoryTable extends DekoTable {

		Button delete;

		public CategoryTable() {
			super();
			String anchor = Store.getFrame().getAdminEditCategory()
					.getAnchor(0);
			Button add = new Button("Add New Category");
			add.addClickListener(new SwitchPage(anchor));
			addTitle("Category");
			addTitle("");
			addTitleWidget(add);
		}

		public void addItem(CategoryVO c) {
			String anchor = Store.getFrame().getAdminEditCategory().getAnchor(
					c.getId());
			Hyperlink edit = new Hyperlink("Edit", anchor);
			AddRow r = addRow();
			r.add(c.getTitle());
			r.add(edit);
			r.add(delete = new Button("Delete"));
			delete.addClickListener(new ButtonClickListener(c));
		}

		public class ButtonClickListener implements ClickListener {
			CategoryVO co = null;

			public ButtonClickListener(CategoryVO c) {
				co = c;
			}

			public void onClick(Widget arg0) {

				OnlinestoreRService.Util.getInstance().disableCategory(
						co.getId(), new DoneAddAsycHandler());
			}
		}

		public class DoneAddAsycHandler extends DefaultAsyncCallback {

			public void onSuccess(Object o) {
				onShow();
			}
		}

	}

	CategoryTable t;

	protected void create() {

		setTitle("Administrate Categories");
		add(t = new CategoryTable());

	}

	protected void onShow() {

		OnlinestoreRService.Util.getInstance().getCategoryList(
				getAsyncHandler());
	}

	protected void onDataArrived(Object o) {

		t.cleanExceptHeader();
		CategoryVO[] cats = (CategoryVO[]) o;
		for (int i = 0; i < cats.length; i++)
			t.addItem(cats[i]);

	}

	public String getID() {
		return "AdminCategories";
	}

}
